<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="user.username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^\w{3,8}$/, message: '3-8位英文数字字母下划线组成' },
        ]"
      />
      <van-field
        v-model="user.pwd"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{3,8}$/, message: '3-8位英文数字字母下划线组成' },
        ]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      <van-button round block type="danger" native-type="reset"> 重置 </van-button>
      <van-button round block @click="router.push('/reg')"> 去注册 </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts" name="UserLogin">
import { reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { userLogin } from "@/api/user";
import { showSuccessToast } from "vant";
import Cookie from "js-cookie";
const router = useRouter();
const route = useRoute();
const user = reactive({
  username: "",
  pwd: "",
});
const onSubmit = () => {
  userLogin({
    ...user,
    deviceId: 22,
    deviceName: "dw",
  }).then((res) => {
    if (res.data.code === 0) {
      Cookie.set("token", res.data.data.token, {
        expires: 7,
      });
      Cookie.set("uid", res.data.data.uid, {
        expires: 7,
      });
      showSuccessToast({
        message: "用户登录成功",
        onClose: () => {
          // 去首页或者被拦截的页面
          if (route.query.from) {
            router.replace(route.query.from as string);
          } else {
            router.replace("/home");
          }
        },
      });
    }
  });
};
</script>

<style scoped></style>
